package com.zy.ems.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.zy.ems.common.base.BaseController;
import com.zy.ems.common.exception.ApiException;
import com.zy.ems.common.util.Md5Util;
import com.zy.ems.common.util.ResultTool;
import com.zy.ems.common.util.StringUtils;
import com.zy.ems.model.UserEntity;
import com.zy.ems.service.UserService;
import com.zy.ems.utils.exceptions.UserCode;

@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;

	@RequestMapping(value = "/doLogin.json", method = RequestMethod.POST)
	public Object login(HttpServletRequest request) {
		String userName = StringUtils.parseStr(request.getParameter("userName"));
		String password = StringUtils.parseStr(request.getParameter("password"));

		try {
			
			if(StringUtils.isEmpty(userName,password)){
				return ResultTool.error(UserCode.B_USER_2001);
			}
			
			UserEntity user = this.userService.login(userName);
			
			if(user == null){
				return ResultTool.error(UserCode.B_USER_2001);
			}
			
			password = Md5Util.getMd5Hex(password);
			
			if(!password.equals(user.getPassword())){
				return ResultTool.error(UserCode.B_USER_2001);
			}
			
			return ResultTool.success("success");

		} catch (ApiException e) {
			return ResultTool.error(e);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			return ResultTool.error(e);
		}
	}
}
